<!-- 重置密码组件 -->
<template>
  <div class="login-container">
    <!-- 背景动画 -->
    <canvas id="forgot-password-bg" class="login-bg"></canvas>

    <!-- 背景渐变层 -->
    <div class="bg-overlay"></div>

    <!-- 装饰元素 -->
    <div class="decoration">
      <div class="palm-tree"></div>
      <div class="sun"></div>
    </div>

    <!-- 重置密码框 -->
    <div class="login-box">
      <div class="login-content">
        <h2 class="title">重置密码</h2>
        <p class="subtitle">请完成邮箱验证以重置密码</p>

        <el-steps :active="currentStep" finish-status="success" simple style="margin: 20px 0 30px;">
          <el-step title="验证邮箱" />
          <el-step title="重置密码" />
          <el-step title="完成" />
        </el-steps>

        <!-- 第一步：验证邮箱 -->
        <div v-if="currentStep === 0">
          <el-form ref="emailFormRef" :model="formData" :rules="emailRules" label-position="top">
            <el-form-item prop="email">
              <el-input
                v-model="formData.email"
                placeholder="邮箱"
                type="email"
                disabled
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="code">
              <div class="verification-wrapper">
                <el-input
                  v-model="formData.code"
                  placeholder="请输入验证码"
                  class="verification-input"
                >
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
                <el-button
                  type="primary"
                  :loading="sending"
                  :disabled="countdown > 0 || sending"
                  @click="sendVerificationCode"
                  class="verification-button"
                >
                  {{ countdown > 0 ? `${countdown}s后重新获取` : (sending ? '发送中...' : '获取验证码') }}
                </el-button>
              </div>
            </el-form-item>
            <div class="form-buttons">
              <el-button @click="goBack">返回登录</el-button>
              <el-button type="primary" @click="verifyEmail">下一步</el-button>
            </div>
          </el-form>
        </div>

        <!-- 第二步：重置密码 -->
        <div v-if="currentStep === 1">
          <el-form ref="passwordFormRef" :model="formData" :rules="passwordRules" label-position="top">
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="formData.newPassword" 
                type="password" 
                placeholder="请输入新密码"
                show-password>
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="formData.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码"
                show-password>
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <div class="form-buttons">
              <el-button @click="currentStep--">上一步</el-button>
              <el-button type="primary" @click="resetPassword">确认重置</el-button>
            </div>
          </el-form>
        </div>

        <!-- 第三步：完成 -->
        <div v-if="currentStep === 2" class="success-step">
          <el-result
            icon="success"
            title="密码重置成功"
            sub-title="您的密码已经重置成功，请使用新密码登录">
            <template #extra>
              <el-button type="primary" @click="goToLogin">返回登录</el-button>
            </template>
          </el-result>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Message, Key, Lock } from '@element-plus/icons-vue'
import { initParticles } from '@/utils/particles'

const router = useRouter()
const route = useRoute()
const currentStep = ref(0)
const countdown = ref(0)
let countdownTimer: number | undefined
const sending = ref(false)

const formData = reactive({
  email: route.query.email as string || '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== formData.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const emailFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

const startCountdown = () => {
  countdown.value = 60
  countdownTimer = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(countdownTimer)
    }
  }, 1000)
}

const sendVerificationCode = async () => {
  if (sending.value) return
  
  try {
    sending.value = true
    // 先验证邮箱格式
    await emailFormRef.value?.validateField('email')
    
    const response = await fetch('/api/auth/forgot-password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ email: formData.email })
    })

    if (!response.ok) {
      throw new Error('发送失败')
    }

    ElMessage.success('验证码已发送到您的邮箱')
    startCountdown()
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '发送验证码失败，请重试')
  } finally {
    sending.value = false
  }
}

const verifyEmail = async () => {
  if (!emailFormRef.value) return
  
  try {
    await emailFormRef.value.validate()
    const response = await fetch('/api/auth/verify-code', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: formData.email,
        code: formData.code
      })
    })
    
    if (response.ok) {
      currentStep.value++
    } else {
      ElMessage.error('验证码错误或已过期')
    }
  } catch (error) {
    console.error('验证失败:', error)
  }
}

const resetPassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    const response = await fetch('/api/auth/reset-password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: formData.email,
        code: formData.code,
        newPassword: formData.newPassword
      })
    })
    
    if (response.ok) {
      currentStep.value++
    } else {
      ElMessage.error('重置密码失败')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
  }
}

const goBack = () => {
  router.push('/login')
}

const goToLogin = () => {
  router.push('/login')
}

// 初始化粒子效果
let cleanup: (() => void) | undefined
onMounted(() => {
  cleanup = initParticles('forgot-password-bg')
})

onBeforeUnmount(() => {
  if (cleanup) {
    cleanup()
  }
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);
  position: relative;
  overflow: hidden;

  .bg-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to bottom,
      rgba(255, 183, 77, 0.2) 0%,
      rgba(255, 167, 77, 0.3) 50%,
      rgba(255, 152, 77, 0.4) 100%
    );
    z-index: 1;
  }

  .decoration {
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 0;
    pointer-events: none;

    .sun {
      position: absolute;
      top: 15%;
      right: 10%;
      width: 100px;
      height: 100px;
      background: radial-gradient(
        circle at center,
        #ffd700 0%,
        #ff8c00 60%,
        transparent 100%
      );
      border-radius: 50%;
      opacity: 0.8;
      animation: glow 3s infinite alternate;
    }

    .palm-tree {
      position: absolute;
      bottom: 0;
      left: 5%;
      width: 200px;
      height: 300px;
      background-image: url('@/assets/palm-tree.png');
      background-size: contain;
      background-repeat: no-repeat;
      background-position: bottom;
      opacity: 0.8;
      transform-origin: bottom;
      animation: sway 5s ease-in-out infinite;
    }
  }

  .login-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
  }

  .login-box {
    position: relative;
    z-index: 3;
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.85);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    animation: slideIn 0.6s ease;

    .login-content {
      .title {
        font-size: 28px;
        font-weight: 600;
        text-align: center;
        margin-bottom: 8px;
        background: linear-gradient(45deg, #ff8c00, #ff6b6b);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
      }

      .subtitle {
        text-align: center;
        color: #666;
        margin-bottom: 32px;
      }

      .verification-wrapper {
        display: flex;
        gap: 10px;
        align-items: stretch;

        .verification-input {
          flex: 1;
        }

        :deep(.verification-button) {
          width: 120px;
          white-space: nowrap;
          height: var(--el-input-height);
          line-height: var(--el-input-height);
          padding: 0;
        }
      }

      .form-buttons {
        display: flex;
        justify-content: space-between;
        margin-top: 30px;
      }

      .success-step {
        text-align: center;
        padding: 20px 0;
      }
    }
  }
}

@keyframes glow {
  from {
    box-shadow: 0 0 20px #ffd700;
  }
  to {
    box-shadow: 0 0 40px #ff8c00;
  }
}

@keyframes sway {
  0%, 100% {
    transform: rotate(-2deg);
  }
  50% {
    transform: rotate(2deg);
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式调整
@media (max-width: 480px) {
  .login-container {
    .login-box {
      width: 90%;
      margin: 0 20px;
      padding: 30px 20px;
    }
  }
}

:deep(.el-input) {
  --el-input-height: 40px;
  
  .el-input__wrapper {
    padding: 0 15px;
  }
  
  .el-input__prefix {
    display: flex;
    align-items: center;
    color: #909399;
  }
}

:deep(.el-steps--simple) {
  background: transparent;
  padding: 0;
  margin: 20px 0;
  
  .el-step__title {
    font-size: 14px;
  }
}

.verification-wrapper {
  .verification-button {
    min-width: 120px;
    transition: all 0.3s;
    
    &:not(:disabled):hover {
      opacity: 0.9;
    }
    
    &:disabled {
      cursor: not-allowed;
      opacity: 0.7;
    }
  }
}
</style> 